package com.wdb.modules.system.rest;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wdb.base.BaseEntity;
import com.wdb.exception.BadRequestException;
import com.wdb.modules.system.domain.Job;
import com.wdb.modules.system.domain.dto.JobExcelDTO;
import com.wdb.modules.system.domain.dto.JobUploadDTO;
import com.wdb.modules.system.domain.vo.JobQueryCriteria;
import com.wdb.modules.system.service.JobService;
import com.wdb.utils.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/3/22 0022 11:01
 */
@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/api/job")
@Api(tags = "职位管理")
public class JobController {
  private final JobService jobService;

  @ApiOperation("列表")
  @GetMapping
  public ResponseEntity<PageResult<Job>> queryJob(JobQueryCriteria criteria, Page<Object> page) {

    return new ResponseEntity<PageResult<Job>>(jobService.queryAll(criteria, page), HttpStatus.OK);
  }

  @ApiOperation("新增")
  @PostMapping
  public ResponseEntity<Object> createJob(@Validated @RequestBody Job job) {
    if (job.getId() != null) {
      throw new BadRequestException("id exist");
    }
    jobService.save(job);
    return new ResponseEntity<>(HttpStatus.OK);
  }

  @ApiOperation("修改")
  @PutMapping
  public ResponseEntity<Object> updateJob(
      @Validated(BaseEntity.Update.class) @RequestBody Job job) {
    jobService.update(job);
    return new ResponseEntity<>(HttpStatus.OK);
  }

  @ApiOperation("删除")
  @DeleteMapping
  public ResponseEntity<Object> deleteJob(@RequestBody Set<Long> ids) {
    // 验证是否被用户关联
    jobService.verification(ids);
    return null;
  }

  @ApiOperation("下载")
  @GetMapping("/download2")
  public void download2(JobQueryCriteria criteria, HttpServletResponse response) throws Exception {
    List<Job> jobList = jobService.queryAll(criteria);
    // 下载
    ArrayList<JobExcelDTO> arrayList = new ArrayList<>();

    for (Job job : jobList) {
      //
      JobExcelDTO jobExcelDTO = new JobExcelDTO();
      jobExcelDTO.setName(job.getName());
      jobExcelDTO.setCreateTime(job.getCreateTime());
      jobExcelDTO.setEnabled(job.getEnabled() ? "启用" : "不启用");
      arrayList.add(jobExcelDTO);
    }
    try {
      // 设置响应类型
      response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
      response.setCharacterEncoding("utf-8");

      // 处理文件名编码
      String fileName = URLEncoder.encode("部门列表", "utf-8");
      response.setHeader(
          "Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

      // 使用 try-with-resources 确保流正确关闭
      try (OutputStream outputStream = response.getOutputStream()) {
        EasyExcel.write(outputStream, JobExcelDTO.class)
            .sheet("列表1") // 考虑使用国际化资源文件或参数化方式
            .doWrite(arrayList);
      }
    } catch (UnsupportedEncodingException e) {
      // 处理编码异常
      System.err.println("编码错误: " + e.getMessage());
    } catch (IOException e) {
      // 处理IO异常
      System.err.println("IO错误: " + e.getMessage());
    }

    log.info("joblist--{}", jobList);
  }

  @ApiOperation("下载")
  @GetMapping("/download")
  public void download(JobQueryCriteria criteria, HttpServletResponse response) throws Exception {
    String templateFileName = "/template/job-excel.xlsx";

    List<Job> jobList = jobService.queryAll(criteria);
    // 下载
    ArrayList<JobExcelDTO> dataList = new ArrayList<>();

    for (Job job : jobList) {
      //
      JobExcelDTO jobExcelDTO = new JobExcelDTO();
      jobExcelDTO.setName(job.getName());
      jobExcelDTO.setCreateTime(job.getCreateTime());
      jobExcelDTO.setEnabled(job.getEnabled() ? "启用" : "不启用");
      dataList.add(jobExcelDTO);
    }
    log.info("datalist--{}", dataList);

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setCharacterEncoding("utf-8");
    String fileName = URLEncoder.encode("部门列表", "utf-8");
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    EasyExcel.write(response.getOutputStream())
        .withTemplate(this.getClass().getResourceAsStream(templateFileName))
        .sheet("列表1")
        .doFill(dataList);
  }

  @ApiOperation("上传")
  @PostMapping("/upload")
  public ResponseEntity<Object> upload(MultipartFile shtList, String name) throws IOException {
    log.info("shtList--{}", shtList.getOriginalFilename());
    EasyExcel.read(
            shtList.getInputStream(), JobUploadDTO.class, new JobEasyExcelDataListener(jobService))
        .sheet()
        .doRead();
    return new ResponseEntity<>(HttpStatus.OK);
  }
}
